package com.qm.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.relational.core.sql.In;
import redis.clients.jedis.*;

import javax.sound.sampled.Port;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 @author james
 @create 2021-04-08 15:38
 */
@Configuration  //我是一个配置类   一般都会与@Bean联用
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {

    @Value("${redis.nodes}")
    private String redisNodes;

    /**
     * 整合redis集群
     * @return
     */
    @Bean
    public JedisCluster jedisCluster() {
        Set<HostAndPort> nodeSet = new HashSet<>();
        String[] nodeArray = redisNodes.split(",");
        for (String node : nodeArray) {
            String host = node.split(":")[0];
            Integer port = Integer.valueOf(node.split(":")[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            nodeSet.add(hostAndPort);
        }
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(10);
        jedisPoolConfig.setMaxIdle(40);
        jedisPoolConfig.setMaxTotal(1000);
        return new JedisCluster(nodeSet,jedisPoolConfig);
    }




    /**
     * 整合分片实现Redis内存扩容
     */
    @Bean
    public ShardedJedis shardedJedis() {
        String[] nodes = redisNodes.split(",");
        List<JedisShardInfo> list = new ArrayList<JedisShardInfo>();
        for (String node: nodes) {
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            list.add(new JedisShardInfo(host,port));
        }
        return new ShardedJedis(list);
    }



    /**
     *单台测试
     */
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;

    @Bean       //将返回值的结果交给spring容器进行管理，如果以后想要使用该对象则可以直接注入
    public Jedis jedis() {
        return new Jedis(host, port);
    }

}
